$NG.AllReady(function (
    editPage,
    { useAction, useValuesChange,useBeforeClick, useDataIndexChange, useUpdateRow , useClick }
) {
	const mstform = $NG.getCmpApi("p_form_gzdyfbsgj");
	const dgrid = $NG.getCmpApi("p_form_gzdyfbsgj_d");

	//添加按钮
	$NG.getCmpApi("toolbar_p_form_gzdyfbsgj_d").insert({
		id: "multipHelp",
		text: "挂接工作单元",
		iconCls: "icon-New",
	});

    useBeforeClick(({args})=>{
        multipHelpClick()
    },"multipHelp")
	//挂接共工作单元逻辑
	function multipHelpClick() {
		const checkArr = dgrid.getSelectedData();
        const phid_pc = $NG.getCmpApi("p_form_gzdyfbsgj").getItem("phid_pc").getValue()
        if(!phid_pc){
            $NG.alert("请选中项目！")
            return
        }
		switch (checkArr.length) {
			case 1:
				//逻辑
				//自定义打开帮助
                if(!checkArr[0].u_fwygcht_name){
                    $NG.alert("选中行没有合同！")
                    break;
                }
				$NG.external
					.openNGHelp({
						type: "NGMultipleHelp",
						helpId: "work_unit",
						valueField: "phid",
						labelField: "u_gzdy_name",
						clientSqlFilter:
                        `m.phid_pc='${phid_pc}'`
						// "ng_phid_cu = " + org + " and user_ssbk=" + 787231124000001,
					})
					.then((data) => {
						console.log(data);
						//data:拿到帮助选中的数据
						multipHelpAddRows(checkArr[0], data);
					});
				break;
			default:
				$NG.alert("请选中一行~");
		}
	}
	//帮助实现多帮助增行逻辑
	async function multipHelpAddRows(row, data) {
		if (!data || data.length == 0) {
			$NG.message("没有选中数据！");
            return
		}
        let error = 0
        //过滤不正常的数据
        data = data.filter(item=>{
            if(item.origin.u_gzdy_code&&item.origin.phid&&item.origin.u_gzdy_name){
                return item
            }else{
                error += 1
            }
        })
        if(error){
            $NG.alert("选中数据有数据不正常，已自动剔除！")
        }
		//准备增行数据
		const _temp = data.reduce((value, item) => {
			const _el = item.origin;
			const _map = { ...row };
			_map.u_gzdy_name = String(_el.phid) || "";
			_map.u_gzdy_name_EXName = String(_el.u_gzdy_name) || "";
			_map.u_gzdy_no = String(_el.u_gzdy_code) || "";
            value.push(_map)
            return value;
		}, []);
        console.log(`_temp`,_temp);
		//判断是否重复挂接
		const darr = dgrid.getRows();
		//查找相同合同已挂接的工作单元
		const _cntphid = row.u_fwygcht_name;
		const cntPhid = darr.reduce((value, item) => {
			if (item.u_fwygcht_name&&item.u_fwygcht_name == _cntphid) {
				value.push(item.u_gzdy_name);
			}
			return value;
		}, []);
        console.log(`cntPhid`,cntPhid);
		//剔除已有工作单元,
		const doneData = _temp.filter((item) => {
			if (cntPhid.indexOf(item.u_gzdy_name) == -1) {
				return item;
			}
		});
        //是否删除选中行
        const _tempAllArr = darr.filter(item=>{
            if(item.checked&&!item.u_gzdy_name){
                console.log(`you`);
            }else {
                return item
            }
        })
        console.log(`_tempAllArr`,_tempAllArr);
        dgrid.clearRows().then(()=>{
            const done = [..._tempAllArr, ...doneData].sort((a,b)=> b - a)
            dgrid.addRows(done);
        })
        console.log(`doneData`,doneData);
	}
	// 监听项目选择的变化
	useValuesChange(({ args }) => {
		console.log(`监听变化的值合同编号`, args);
	}, "p_form_gzdyfbsgj.u_pc_no");

	// 监听项目选择的变化
	useValuesChange(({ args }) => {
		cntDFilter();
		console.log(`监听变化的值合同名称`, args);
		const phID = args[0].phid_pc.PcNo;
		$NG.updateState((updater) => {
			updater.data.p_form_gzdyfbsgj.setProps({
				u_pc_no: phID,
			});
		});
		cntMFilter();
		dgrid.clearRows();
	}, "p_form_gzdyfbsgj.phid_pc");
	// 监听表格中合同名称的变化
	useDataIndexChange(({ args }) => {
		console.log(`监听表格数据的变化`, args);
        args[0].u_gzdy_name = null
        args[0].u_gzdy_name_EXName = null
        args[0].u_gzdy_no = null
		getCntInfo(args);
	}, "u_fwygcht_name");
	useDataIndexChange(({ args }) => {
		console.log(`监听表格数据的变化`, args);
		$NG.execServer(
			"getGzdyqdByPhid",
			{ phid: args[0].u_gzdy_name },
			(res) => {
				const _data = JSON.parse(res.data)[0].extendObjects;
				args[0].u_gzdy_no = _data.u_gzdy_code;
			}
		);
		dgrid.refreshView();
	}, "u_gzdy_name");
	useDataIndexChange(({ args }) => {
		console.log(args);
		getGzdynoById(args[0].u_gzdy_name, (code) => {
			args[0].u_gzdy_no = code;
			dgrid.refreshView();
		});
	}, "u_gzdy_name");
	// 根据id获取编码
	function getGzdynoById(phid, fun) {
		$NG.execServer("getGzdynoById", { phid }, function (res) {
			if (res.count == 0) return;
			const _data = JSON.parse(res.data)[0].extendObjects;
			fun(_data.u_gzdy_code);
		});
	}
	// 根据主类的项目id获取合同
	cntDFilter();
	function cntDFilter() {
		const phid_pcc = $NG
			.getCmpApi("p_form_gzdyfbsgj")
			.getItem("phid_pc")
			.getValue();
		console.log(`项目id`, phid_pcc);
		if (!phid_pcc) {
			return;
		}
		$NG.updateUI((updater) =>
			updater.editGrid.p_form_gzdyfbsgj_d.u_fwygcht_name.setProps((p) => {
				return {
					...p,
					editor: {
						...p.editor,
						clientSqlFilter: {
							phid_pc: $NG
								.getCmpApi("p_form_gzdyfbsgj")
								.getItem("phid_pc")
								.getValue(),
						},
					},
				};
			})
		);
	}
	cntMFilter();
	function cntMFilter() {
		const phid_pcc = $NG
			.getCmpApi("p_form_gzdyfbsgj")
			.getItem("phid_pc")
			.getValue();
		if (!phid_pcc) {
			return;
		}
		$NG.updateUI((updater) =>
			updater.editGrid.p_form_gzdyfbsgj_d.u_gzdy_name.setProps((p) => {
				return {
					...p,
					editor: {
						...p.editor,
						clientSqlFilter: {
							"m.phid_pc": $NG
								.getCmpApi("p_form_gzdyfbsgj")
								.getItem("phid_pc")
								.getValue(),
						},
					},
				};
			})
		);
	}
	function getCntInfo(arg) {
		$NG.execServer(
			"getCntMInfoByPhid",
			{ phid: arg[0].u_fwygcht_name },
			function (res) {
				const datas = JSON.parse(res.data)[0].extendObjects;
				console.log(`合同：`, datas);
				//帮助字段赋值
				arg[0].u_fwygcht_no = datas.pcm_no;
				arg[0].u_wbs_name = datas.supply_id;
				arg[0].u_wbs_name_EXName = datas.supply_name;
				arg[0].u_wbgys_no = datas.supply_no;
				dgrid.refreshView();
			}
		);
	}
});